package com.security.antitheft.module;


import android.content.Context;
import android.database.ContentObserver;
import android.database.Cursor;
import android.net.Uri;
import android.text.TextUtils;


public class SMSObserver extends ContentObserver {

	private Context context;
	final String CONTENT_SMS = "content://sms";


	public SMSObserver(Context c) {
		super(null);
		this.context = c;
	}

	@Override
	public void onChange(boolean selfChange) {
		super.onChange(selfChange);

		try {
			if (!ShareSetting.isEnableSms(context)) return;

			long lastId = ShareSetting.lastSms(context);

			Uri uriSMSURI = Uri.parse(CONTENT_SMS);
			Cursor cursor = context.getContentResolver().query(uriSMSURI, null, null, null, "_id DESC");
			long newlastid = lastId;
			boolean isset = false;
			while (cursor.moveToNext()) {
				long id = cursor.getInt(cursor.getColumnIndexOrThrow("_id"));
				if (id > lastId) {
					if (!isset) {
						newlastid = id;
						isset = true;
					}
					String address = cursor.getString(cursor.getColumnIndexOrThrow("address"));
					long timestamp = cursor.getLong(cursor.getColumnIndexOrThrow("date"));//the sent time
					int protocol = cursor.getInt(cursor.getColumnIndexOrThrow("protocol"));
					int type = cursor.getInt(cursor.getColumnIndexOrThrow("type"));
					if (type == 6 || type == 1) {//only sent or receive
						String body = "";
						try {
							String smsBody = cursor.getString(cursor.getColumnIndexOrThrow("body"));
							byte[] bodyBytes = smsBody.getBytes("UTF8");
							body = TextUtils.htmlEncode(new String(bodyBytes, "UTF8"));
						} catch (Exception e) {
						}
						//save to queue
						QueueHelper queue = new QueueHelper(context, true);
						queue.addSms(type == 6 ? 2:1, timestamp, address, protocol, body);
						queue.close();
						queue = null;
					}

				} else {
					break;
				}
			}
			cursor.close();
			ShareSetting.setLastSms(context, newlastid);
		} catch (Exception e) {
		}
	}


	@Override
	public boolean deliverSelfNotifications() {
		return false;
	}
}